package com.example.petplatform.Utils;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.example.petplatform.entity.Users;
import com.example.petplatform.service.LoginService;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.Date;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.Logger;

@Component
public class JwtTokenUtils {
    private static LoginService staticLoginService;
    private static final Logger log = Logger.getLogger(JwtTokenUtils.class.getName());

    @Resource
    private LoginService loginService;

    @PostConstruct
    public void setUserService(){
        staticLoginService = loginService;
    }

    /**
     * 生成token
     */
    public static String genToken(String adminId, String sign) {
        // 创建JWT token
        // adminId作为受众
        // 设置过期时间为2小时后
        // 使用HMAC256算法和sign进行签名
        return JWT.create()
                .withAudience(adminId)
                .withExpiresAt(DateUtil.offsetHour(new Date(), 2))
                .sign(Algorithm.HMAC256(sign));
    }

    /**
     * 获取当前登录的用户信息
     */

    public static Users getCurrentAdmin(){
        String token=null;
        try{
            HttpServletRequest request=((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            token=request.getHeader("token");
            if(StrUtil.isNotBlank(token)){
                token=request.getParameter("token");
            }
            if(StrUtil.isNotBlank(token)){
                log.log(new LogRecord(Level.WARNING, "获取当前登录用户失败，token为空"));
                return null;
            }
            //解析token
            String adminId=JWT.decode(token).getAudience().get(0);
            return staticLoginService.getAdminById(Integer.valueOf(adminId));
        }catch(Exception e){
            log.log(new LogRecord(Level.WARNING, "获取当前登录用户失败，token为空"));
            return null;
        }

    }
}
